package com.lry.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * Excel读取监听器
 *
 * @author ALI
 * @since 2021/12/13
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class ExcelReaderListener extends AnalysisEventListener<Map<Integer, String>> {

    private List<List<String>> data = new ArrayList<>();

    /**
     * 按每个sheet存放读取的数据
     * map 实体
     * key  sheet
     * value 每一行的数据
     */
    private List<Table> result = new ArrayList<>();

    @Override
    public void invoke(Map<Integer, String> integerStringMap, AnalysisContext analysisContext) {
        data.add(new ArrayList<>(integerStringMap.values()));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<String> header;
        header = data.get(0);
        List<List<Field>> rowDataMap = new ArrayList<>();
        for (int i = 1; i < data.size(); i++) {
            List<String> rowData = data.get(i);
            List<Field> tempColumn = new ArrayList<>();
            for (int j = 0; j < rowData.size(); j++) {
                if (j >= header.size()) {
                    break;
                }
                String rowValue = rowData.get(j);
                tempColumn.add(new Field(header.get(j), rowValue));
            }
            rowDataMap.add(tempColumn);
        }
        result.add(new Table(analysisContext.readSheetHolder().getSheetName(), rowDataMap));
        data.clear();
    }

    public void destory() {
        this.data.clear();
        this.result.clear();
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Table {

        private String sheetName;

        private List<List<Field>> field;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Field {

        /** 字段名 */
        private String key;

        /** 字段值 */
        private String value;
    }
}
